package own.stu.jobgib.playown.util.beanCopy;

import org.springframework.cglib.beans.BeanCopier;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BeanCopyUtil {

    private final static Map<String, BeanCopier> beanCopierCacheMap = new ConcurrentHashMap<>();

    /**
     * 将source对象的属性拷贝到target对象中去
     * @param source source对象
     * @param target target对象
     */
    public static void copyProperties(Object source, Object target) {
        String cacheKey = source.getClass().toString() + target.getClass().toString();

        BeanCopier beanCopier;
        if (!beanCopierCacheMap.containsKey(cacheKey)) {
            synchronized (BeanCopyUtil.class) {
                if (!beanCopierCacheMap.containsKey(cacheKey)) {
                    beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
                    beanCopierCacheMap.put(cacheKey, beanCopier);
                } else {
                    beanCopier = beanCopierCacheMap.get(cacheKey);
                }
            }
        } else {
            beanCopier = beanCopierCacheMap.get(cacheKey);
        }
        beanCopier.copy(source, target, null);
    }
    /*public static void main(String[] args) {
//        BeanCopier beanCopier = BeanCopier.create(Student.class, StudentDTO.class, false);
        Student student = new Student();
        student.setAge(10);
        student.setId(1L);
        student.setName("xss");
        student.setFriends(geneFriends());

        StudentDTO studentDTO = new StudentDTO();
//        beanCopier.copy(student, studentDTO, null);
        BeanCopyUtil.copyProperties(student, studentDTO);
        System.out.println(student.getFriends() == studentDTO.getFriends());
        System.out.println(studentDTO);
    }

    static List<Student> geneFriends(){
        Student student = new Student();
        student.setAge(11);
        student.setId(2L);
        student.setName("F1");

        return Lists.newArrayList(student);
    }*/
}
